package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
@ResponseBody
//处理全局异常类
public class GlobalExceptionHandler {
    /**
     * 异常处理该方法；
     * @param
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException sql) {

        String message = sql.getMessage();
        if (message.contains("Duplicate entry")) {
            String[] s = message.split(" ");
            String s1 = s[2];
            return R.error(s1 + "已存在");
        }
        return R.error("未知错误");
    }

    /**
     * 自定义异常
     * @param c
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> customException(CustomException c){
        String message = c.getMessage();
        return R.error(message);
    }
}
